package com.platform.qujia.controller;

import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.*;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.gson.Gson;
import com.platform.qujia.constantEnum.DecimalConstant;
import com.platform.qujia.dao.AppUserSuperCopyMapper;
import com.platform.qujia.dao.PayOrderMapper;
import com.platform.qujia.dao.StationMapper;
import com.platform.qujia.param.request.RechargeBalance;
import com.platform.qujia.pojo.*;
import com.platform.qujia.pojo.dto.DivideAccountsSettingDto;
import com.platform.qujia.service.*;
import com.platform.qujia.utils.CodeMsg;
import com.platform.qujia.utils.RSASignature;
import com.platform.qujia.utils.ResultData;
import com.platform.qujia.utils.SXFPaySign;
import com.platform.qujia.utils.jinkong.JKPayUtil;
import com.platform.qujia.utils.sxfpay.SXFPayParam;
import com.platform.qujia.utils.sxfpay.SXFPayUtil;
import com.platform.qujia.utils.tonglianpay.SybConstants;
import com.platform.qujia.utils.tonglianpay.SybUtil;
import com.platform.qujia.utils.tonglianpay.TLPayParam;
import com.platform.qujia.utils.tonglianpay.TLPayUtil;
import com.platform.qujia.utils.tonglianpay.tlfusclasspay.TLFusClassPayUtil;
import com.platform.qujia.utils.tonglianpay.tlfusclasspay.struct.body.TLFusClassPayParam;
import com.platform.qujia.utils.weixinapp.WxPushUtil;
import com.platform.qujia.utils.yunHua.YunHuaParam;
import com.platform.qujia.utils.yunHua.yunHuaPayUtils;
import com.platform.qujia.utils.yunpay.SBPayParam;
import com.platform.qujia.utils.yunpay.SBPayUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import net.bytebuddy.implementation.bind.annotation.Super;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;


import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 超级会员开通支付订单Controller
 *
 * @author qujia
 * @date 2021-12-20
 */
@RestController
@Api(tags = "趣加超级会员功能")
@CrossOrigin
public class SuperPayOrderController
{
    private static Logger logger =(Logger) LoggerFactory.getLogger(QuJiaPayController.class);

    @Resource
    private SuperPayOrderService superPayOrderService;
    @Resource
    private AppUserInfoService appUserInfoService;
    @Resource
    private AppUserSuperService appUserSuperService;
    @Resource
    private EnterpriseService enterpriseService;
    @Resource
    private ElectronicMembershipCardService electronicMembershipCardService;
    @Resource
    private GzhNewsTemplateService gzhNewsTemplateService;
    @Resource
    private WxPushUtil wxPushUtil;
    @Resource
    private AppUserSuperDetailService appUserSuperDetailService;
    @Resource
    private StationMapper stationMapper;
    @Autowired
    private AppUserSuperCopyService appUserSuperCopyService;
    @Resource
    private PayOrderMapper payOrderMapper;


    @Value("${server.servlet.context-path}")
    private String contextPath;

    @Value("${qujia.domainName}")
    private String domainName;
    @Value("${qujia.yunhuaPrePayUrl}")
    private String yunHuaPrePayUrl;

    //查询超级会员
    @Transactional
    @PostMapping("/appUserSuperList")
    @ApiOperation(value = "查询超级会员")
    public String appUserSuperList(@RequestBody AppUserSuper appUserSuper){

        Gson gson =new Gson();
        //返回结果集
        ResultData resultData = null;
        appUserSuper.setEnable(0);
        List<AppUserSuper> appUserSuperList = appUserSuperService.getAppUserSuperList(appUserSuper);
        for (AppUserSuper userSuper : appUserSuperList) {
            if (StringUtils.isBlank(userSuper.getShowName())) {
                userSuper.setShowName(userSuper.getSuperName());
            }
            if (userSuper.getSuperUserTerm() == null) {
                userSuper.setSuperUserTerm("");
            }
        }
        return gson.toJson(ResultData.success(appUserSuperList));
    }

    @GetMapping("/queryAppUserSuperCopy")
    @ApiOperation("查询超级会员预热文案")
    public ResultData<String> queryAppUserSuperCopy(@RequestParam Integer enterpriseId){
        AppUserSuperCopy form = new AppUserSuperCopy();
        form.setEnterpriseId(enterpriseId);
        QueryWrapper<AppUserSuperCopy> qw = new QueryWrapper<>(form);
        qw.last("limit 1");
        AppUserSuperCopy appUserSuperCopy = appUserSuperCopyService.getOne(qw);
        if (appUserSuperCopy == null) {
            return ResultData.success("");
        }
        return ResultData.success(appUserSuperCopy.getPreheatCopy());
    }

    @GetMapping("/queryAppUserSuperAgreement")
    @ApiOperation("查询超级会员协议")
    public ResultData<String> queryAppUserSuperAgreement(@RequestParam Integer enterpriseId){
        AppUserSuperCopy form = new AppUserSuperCopy();
        form.setEnterpriseId(enterpriseId);
        QueryWrapper<AppUserSuperCopy> qw = new QueryWrapper<>(form);
        qw.last("limit 1");
        AppUserSuperCopy appUserSuperCopy = appUserSuperCopyService.getOne(qw);
        if (appUserSuperCopy == null) {
            return ResultData.success("");
        }
        return ResultData.success(appUserSuperCopy.getSuperUserAgreement());
    }

    //查询用户身份
    @Transactional
    @PostMapping("/appUserSuperDetail")
    @ApiOperation(value = "查询用户身份")
    public String appUserSuperDetail(@RequestBody AppUserSuperDetail appUserSuperDetail){
        //返回结果集
        ResultData resultData = null;
        Gson gson =new Gson();
        //获取用户信息
        AppUserInfo appUserInfoResult = appUserInfoService.getAppUserInfo(AppUserInfo.builder().mobilePhone(appUserSuperDetail.getMobilePhone())
                        .stationId(Integer.valueOf(appUserSuperDetail.getEnterpriseId().toString())).build());
        if(appUserInfoResult == null){
            return gson.toJson(ResultData.error(CodeMsg.USER_NOT_EXSIST));
        }

        List<AppUserSuperDetail> appUserSuperDetails = appUserSuperDetailService.selectAppUserSuperDetailList(AppUserSuperDetail.builder()
                .enterpriseId(appUserSuperDetail.getEnterpriseId())
                .userId(Long.valueOf(appUserInfoResult.getUserId())).beginDate(new Date()).endDate(new Date()).build());
        if(appUserSuperDetails != null && appUserSuperDetails.size() == 1){
            appUserSuperDetail = appUserSuperDetails.get(0);
            if(appUserSuperDetail != null){
                Long superId = appUserSuperDetail.getSuperId();
                AppUserSuper appUserSuper = appUserSuperService.selectAppUserSuperById(superId);
                if(appUserSuper.getCouponIssueId() != null){
                    resultData = ResultData.success(appUserSuper.getCouponIssueId());
                    return gson.toJson(resultData);
                }
            }
        }else{
            return gson.toJson(ResultData.success(null));
        }
        return gson.toJson(ResultData.success(null));
    }

    //用户开通超级会员生成支付记录
    @Transactional
    @PostMapping("/createSuperPayOrder")
    @ApiOperation(value = "用户开通超级会员生成支付记录")
    public String rechargeBalance(@RequestBody SuperPayOrder superPayOrder){
        logger.info("超级会员id："+ superPayOrder.getSuperId() + "; 开通手机号："+superPayOrder.getMobilePhone());
        Gson gson =new Gson();
        //返回结果集
        ResultData resultData = null;
        if(superPayOrder !=null && superPayOrder.getSuperId() != null &&
                StringUtils.isNotBlank(superPayOrder.getMobilePhone())){
            //开通的超级会员类型
            AppUserSuper appUserSuper = appUserSuperService.selectAppUserSuperById(superPayOrder.getSuperId());
            //获取用户信息
            AppUserInfo appUserInfoResult = appUserInfoService.getAppUserInfo(AppUserInfo.builder()
                                    .stationId(Integer.valueOf(appUserSuper.getEnterpriseId().toString())).mobilePhone(superPayOrder.getMobilePhone()).build());


            //TODO 判断之前的超级会员类型，年卡会员不能开通月卡
            List<AppUserSuperDetail> appUserSuperDetails = appUserSuperDetailService.selectAppUserSuperDetailList(AppUserSuperDetail.builder().enterpriseId(appUserSuper.getEnterpriseId())
                    .userId(Long.valueOf(appUserInfoResult.getUserId().toString())).build());
//            AppUserSuperDetail appUserSuperDetail = appUserSuperDetailService.selectAppUserSuperDetailById(Long.valueOf(info.getUserId().toString()));
            AppUserSuperDetail appUserSuperDetail = null;
            if(appUserSuperDetails != null && appUserSuperDetails.size()>0){
                appUserSuperDetail = appUserSuperDetails.get(0);
                Long superId = appUserSuperDetail.getSuperId();
                AppUserSuper oldSuper = appUserSuperService.selectAppUserSuperById(superId);
                if(oldSuper != null){
                    if((oldSuper.getCycle()-10)>appUserSuper.getCycle()){
                        CodeMsg codeMsg = new CodeMsg(1, "已经是"+oldSuper.getSuperName() + "会员，不能开通" + appUserSuper.getSuperName());
                        resultData = ResultData.error(codeMsg);
                        return gson.toJson(resultData);
                    }
                }
            }
            Date now = new Date();
            if (appUserSuperDetail != null) {
                Date endDate = appUserSuperDetail.getEndDate();
                if (endDate != null && now.before(endDate)) {
                    now = endDate;
                }
            }
            Calendar cal = Calendar.getInstance();
            cal.setTime(now);
            cal.add(Calendar.DATE,  appUserSuper.getCycle().intValue());
            String orderNo = System.currentTimeMillis() + RandomStringUtils.randomNumeric(6);    //订单号 时间+6位随机数
            superPayOrderService.insertSuperPayOrder(SuperPayOrder.builder()
                    .superOrderNo(orderNo)
                    .amt(appUserSuper.getPrice())
                    .appUserId(appUserInfoResult.getUserId())
                    .appUserName(appUserInfoResult.getBlogNickName())
                    .superId(appUserSuper.getSuperId())
                    .superName(appUserSuper.getSuperName())
                    .createTime(now)
                    .status("0")
                    .mobilePhone(superPayOrder.getMobilePhone())
                    .stationId(superPayOrder.getStationId())
                    .enterpriseId(Math.toIntExact(appUserSuper.getEnterpriseId()))
                    .cycle(appUserSuper.getCycle())
                    .superStartTime(now)
                    .superEndTime(cal.getTime())
                    .build());

            logger.info( superPayOrder.getMobilePhone() + " 超级会员的开通单号：" +orderNo);
            resultData = ResultData.success(orderNo);
        }else {
            resultData = ResultData.error(CodeMsg.PARAMS_NUll);
        }
        return gson.toJson(resultData);
    }


    //开通超级会员拉起第三方支付
    @RequestMapping(value = "/appUserSuperToThirdPayment", method = RequestMethod.POST)
    @ApiOperation(value = "公众号充值拉起第三方支付", httpMethod = "POST", notes = "开通超级会员拉起第三方支付")
    public String rechargeToThirdPayment(@RequestBody RechargeBalance rechargeBalance) throws Exception {
        Gson gson = new Gson();
        ResultData resultData = null;
        if(rechargeBalance !=null && StringUtils.isNotBlank(rechargeBalance.getOpenId()) && rechargeBalance.getEnterpriseId() !=null
                && StringUtils.isNotBlank(rechargeBalance.getUserType()) && StringUtils.isNotBlank(rechargeBalance.getOrderNo())) {
            //String amt = rechargeBalance.getAmt();
            String openId = rechargeBalance.getOpenId();    //公众号的openId
            String userType = "1";
            String ordNo = rechargeBalance.getOrderNo();
            //根据油企查出一个油站
//            Station station = new  Station();
//            station.setEnterpriseId(rechargeBalance.getEnterpriseId());
//            List<Station> stations = stationMapper.selectStaInfoList(station);
//            if(stations != null && stations.size()>0){
//                stationId = stations.get(0).getStationId();
//            }

            SuperPayOrder superPayOrder = null;
            SuperPayOrder payOrder = new SuperPayOrder();
            payOrder.setSuperOrderNo(ordNo);
            payOrder.setStatus("0");
            List<SuperPayOrder> superPayOrders = superPayOrderService.selectSuperPayOrderList(payOrder);
            if(superPayOrders != null && superPayOrders.size() == 1){
                superPayOrder = superPayOrders.get(0);
            }
            if(superPayOrder !=null ){
                if(superPayOrder.getStatus() !=null && superPayOrder.getStatus().equals("0")){
                    //获取油站的支付配置项信息

                    PayWay payWay = new PayWay();
                    payWay.setStationId(superPayOrder.getStationId());
                    payWay.setEnterpriseId(rechargeBalance.getEnterpriseId());
                    payWay.setAppType(userType);        //支付宝还是微信
                    payWay.setUseType("0");             //使用类型
                    //获取该油站的支付类型
                    List<PayWay> payWayList = null;
                    if(rechargeBalance.getEnterpriseId() != null){
                        payWayList = enterpriseService.selectStaPayWay(payWay);
                    }
                    HashMap<String, Object> resultMap = new HashMap<>();
                    if(payWayList !=null && payWayList.size() >= 1){
                        payWay = payWayList.get(0);
                        //当前油站的支付方式 是随行付还云闪付
                        String payTypeSta = payWayList.get(0).getPayType();
                        String mno = payWayList.get(0).getMno();    //商户号
                        String cardName ="开通";
                        superPayOrder.setPayType("wx");
                        superPayOrder.setPayWayId(payWayList.get(0).getPayWayId());
                        if(payWay.getServiceCharge() != null){
                            //superPayOrder.setServiceCharge(superPayOrder.getAmt().divide(new BigDecimal(1000),4,BigDecimal.ROUND_HALF_UP).multiply(payWay.getServiceCharge()));
                            superPayOrder.setServiceCharge(superPayOrder.getAmt().multiply(DecimalConstant.O_001).multiply(payWay.getServiceCharge()).setScale(2, RoundingMode.HALF_UP));
                        }
                        String subject = cardName+  " - " +superPayOrder.getSuperName();
                        String notifyUrl = "";
                        //公众号
                        String appId  = payWayList.get(0).getEnterprise().getGzhAppId();
                        switch (payTypeSta){
                            case "1":   //随行付
                                SXFPayParam sxfPayParam = new SXFPayParam();

                                sxfPayParam.setAmt(superPayOrder.getAmt().toString());
                                sxfPayParam.setAppId(appId);
                                sxfPayParam.setMno(mno);
                                sxfPayParam.setOrdNo(ordNo);
                                //notifyUrl = "https://"+domainName+"/" +"apipay/getCardRechargeCallback";
                                notifyUrl = "https://"+domainName+"/" + contextPath+"/getSVIPCallback";
                                sxfPayParam.setNotifyUrl(notifyUrl);
                                sxfPayParam.setSubject(subject);
                                sxfPayParam.setUserId(openId);
                                sxfPayParam.setUserType(userType);
                                sxfPayParam.setWeChatType("2");

                                String ledgerAccountFlag = "0";

                                sxfPayParam.setLedgerAccountFlag(ledgerAccountFlag);
                                resultMap = SXFPayUtil.tradeJsApiScan(sxfPayParam);
                                break;
                            case "2":   //圈圈（元闪付，扫呗）
                                SBPayParam sbPayParam = new SBPayParam();
                                sbPayParam.setAmt(superPayOrder.getAmt().toString());
                                sbPayParam.setAppId(appId);
                                sbPayParam.setUserType(userType);
                                sbPayParam.setAppPayType("2");
                                String secretKey = payWayList.get(0).getSecretKey();
                                sbPayParam.setKey(secretKey);
                                sbPayParam.setOpenId(openId);
                                String terminalNo = payWayList.get(0).getTerminalNo();
                                sbPayParam.setTerminalId(terminalNo);
                                sbPayParam.setOrdNo(ordNo);
                                sbPayParam.setOrderBody(subject);
                                //notifyUrl = "https://"+domainName+"/"+"apipay/getYunPayGzhCallback";
                                notifyUrl = "https://"+domainName+"/"+contextPath+"/getYunPaySVIPCallback";
                                sbPayParam.setNotifyUrl(notifyUrl);
                                sbPayParam.setMerchantNo(mno);
                                resultMap = SBPayUtil.saoBeiTradePay(sbPayParam);
                                break;
                            case "3":   //通联支付
//                                if(null != payWayList.get(0).getTlFusFlag() && "1".equals(payWayList.get(0).getTlFusFlag())){
//                                    long amtLong = new BigDecimal(superPayOrder.getAmt().toString()).multiply(new BigDecimal("100")).longValue();
//                                    notifyUrl = "https://"+domainName + contextPath + "/getTLFusClassSVIPPayCallback";     //回调地址
//                                    String tlFusClassPayType = "WECHAT_PUBLIC";
//                                    logger.info("超级会员开通充值 payway支付参数信息：" + payWayList.get(0).getPayWayId());
//                                    //获取通联支付的班次标识
//                                    String shiftsMask ="";
//                                    String shiftsTime ="";
//                                    Map<String, String> smat = this.getShiftsMaskAndTime(payWayList.get(0).getPayWayId());
//                                    if(null != smat && smat.containsKey("shiftsMask") && smat.containsKey("shiftsTime")){
//                                        shiftsMask = smat.get("shiftsMask");
//                                        shiftsTime = smat.get("shiftsTime");
//                                    }else {
//                                        logger.info("超级会员开通充值 未设置班次");
//                                    }
//                                    logger.info("超级会员开通充值班次标识：" + shiftsMask + "; 超级会员开通充值 班次时间：" + shiftsTime);
//                                    resultMap = TLFusClassPayUtil.tLFusClassPayApply(
//                                            TLFusClassPayParam.builder()
//                                                    .account(openId)                        //oWL5P5PPF5gFmoDid19Ij_nN5h70  openId oRwjv4iHjSUgxNxOJOQ_60Ln7cno
//                                                    .amount(amtLong)
//                                                    .backUrl(notifyUrl)
//                                                    .bizOrderNo(ordNo)
//                                                    .sysId(payWayList.get(0).getTlSysId())
//                                                    .tlAppId(payWayList.get(0).getTlAppId())
//                                                    .tlAppKey(payWayList.get(0).getTlAppKey())
//                                                    .tlOilStationNo(payWayList.get(0).getTlOilStationNo())                 //通联支付所需要的油站编码
//                                                    .consumeType("C0001")                                                  //消费类型
//                                                    .shiftsMask(shiftsMask)                                                //班次标识
//                                                    .shiftsTime(shiftsTime)     //班次时间
//                                                    .remark(subject)
//                                                    .subAppId(appId)                            //wxb46701bd193ee573 appId wxe1135cd390b38a54
//                                                    .payType(tlFusClassPayType)
//                                                    .build());
//                                }else {
                                    notifyUrl = "https://"+domainName + contextPath + "/tLSVIPPayCallback";
                                    resultMap = TLPayUtil.tLTradePay(
                                            TLPayParam.builder()
                                                    .body(subject)
                                                    .notifyUrl(notifyUrl)
                                                    .remark(subject)
                                                    .reqSn(ordNo)
                                                    .payType("W06")         //"wx".equals(payType) ? "W06" : "A02"
                                                    .acct(openId)           //微信用户openId
                                                    .subAppId(appId)        //微信appId
                                                    .sybAppId(payWayList.get(0).getAllinpayAppId())           //通联系统分配的appId 00226421 payWayList.get(0).getAllinpayAppId()
                                                    .SIGN_TYPE("RSA")       //通联验签加密方式  RSA； SM2； MD5；
                                                    .SYB_RSACUSPRIKEY(payWayList.get(0).getAllinpayRSAKey())   //秘钥 RSA； SM2； MD5；
                                                    .cusId(mno)             //商户号
                                                    .trxAmt(new BigDecimal(payOrder.getAmt().toString()).multiply(new BigDecimal("100")).longValue())  //单位分
                                                    .build());
                                //}
                                break;
                            case "5":
                                logger.info("超级会员充值单号为：{}，金额：{}",superPayOrder.getSuperOrderNo(),superPayOrder.getAmt());
                                notifyUrl = "https://"+domainName+"/" + contextPath+"/getSVIPYunhuaCallback";
                                String userId="";
                                AppUserInfo appUserInfo=appUserInfoService.getById(superPayOrder.getAppUserId());
                                if (appUserInfo != null) {
                                    if(appUserInfo.getYunhuaUserId()!=null){
                                        userId=appUserInfo.getYunhuaUserId();
                                    }else {
                                        userId=appUserInfo.getMobilePhone();
                                    }
                                }
                                String txnDesc = "（未知）";
                                if(superPayOrder.getSuperName()!=null){
                                    txnDesc = "超级会员-"+superPayOrder.getSuperName();
                                }

                                resultMap= yunHuaPayUtils.yunHuaPayV2(YunHuaParam.builder()
                                        .partnerCode(payWayList.get(0).getMno())
                                        .posOrderNo(ordNo)
                                        .noticeUrl(notifyUrl)
                                        .txnDesc(txnDesc)
                                        .txnAmt(superPayOrder.getAmt())
                                        .userId(userId)
                                        .build(),payWayList.get(0).getSecretKey(),yunHuaPrePayUrl);
                                resultMap.put("merchantsNumber","111111");
                                break;
                        }
                        resultMap.put("thirdPayment", payTypeSta);
                        resultData = ResultData.success(resultMap);
                    }else {
                        resultData = ResultData.error(CodeMsg.NOT_PAYWAY);
                    }
                }else {
                    resultData = ResultData.error(CodeMsg.ALREADY_PAY);
                }
                superPayOrderService.updateSuperPayOrder(superPayOrder);
            }else {
                resultData=ResultData.error(CodeMsg.YEWU_FAIL,"未查询到订单");
            }
        }
        return gson.toJson(resultData);
    }

    /*
     * 超级会员公众号消费 通联智U+，需要实时到账，分账时 获取班次时间与班次标识
     * @param payWayId
     * @return
     * @throws ParseException
     */
    public Map<String, String> getShiftsMaskAndTime(Integer payWayId) throws ParseException {
        Map<String, String> resultMap = new HashMap<>();
        if(null != payWayId){
            String shiftsMask ="";
            String shiftsTime ="";
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            List<ShiftClass> shiftClassList = enterpriseService.selectShiftClassList(ShiftClass.builder().payWayId(payWayId).build());
            if(null != shiftClassList && shiftClassList.size()>0){
                for (ShiftClass sc : shiftClassList){
                    //如果开始时间小于结束时间，做处理
                    if(sc.getShiftStartTime().compareTo(sc.getShiftEndTime()) <=0){
                        Date sst = sdf.parse(LocalDate.now().toString() + " " + sc.getShiftStartTime().toString());
                        Date set = sdf.parse(LocalDate.now().toString() + " " + sc.getShiftEndTime().toString());
                        if(new Date().compareTo(sst) >=0 && new Date().compareTo(set) <0){
                            shiftsMask = sc.getShiftMask();
                            shiftsTime = DateFormatUtils.format(new Date(), "yyyyMMdd");
                            break;
                        }
                    }else {
                        //否则
                        Date sst = sdf.parse(LocalDate.now().toString() + " " + sc.getShiftStartTime().toString());
                        Date set = sdf.parse(LocalDate.now().plusDays(1).toString() + " " + sc.getShiftEndTime().toString());
                        if(new Date().compareTo(sst) >=0 && new Date().compareTo(set) <0){
                            shiftsMask = sc.getShiftMask();
                            shiftsTime = DateFormatUtils.format(new Date(), "yyyyMMdd");
                            if(new Date().compareTo(sdf.parse(LocalDate.now().toString() + " " + "23:59:59")) > 0){
                                shiftsTime = LocalDate.now().plusDays(-1).toString().replace("-", "");
                            }
                            break;
                        }
                    }
                }
            }
            logger.info("shiftsMask：" + shiftsMask + "; shiftsTime:" + shiftsTime);
            resultMap.put("shiftsMask", shiftsMask);
            resultMap.put("shiftsTime", shiftsTime);
        }
        return resultMap;
    }

//    @RequestMapping(value = "/getTLFusClassSVIPPayCallback", consumes = "application/x-www-form-urlencoded", method = RequestMethod.POST)
//    @Transactional
//    public void getTLFusClassSVIPPayCallback(HttpServletRequest request, HttpServletResponse response) throws Exception {
//        logger.info("========================================公众号电子卡通联智U+，需要实时到账，分账时预支付接口 回调开始 ========================================");
//        System.out.println("公众号电子卡通联支付接收到通知");
//        request.setCharacterEncoding("UTF-8");//通知传输的编码为GBK
//        response.setCharacterEncoding("UTF-8");
//        TreeMap<String, String> params = getParams(request);//动态遍历获取所有收到的参数,此步非常关键,因为收银宝以后可能会加字段,动态获取可以兼容
//        logger.info("公众号电子卡通联智U+，需要实时到账，分账返回TreeMap参数：" + params.toString());
//        try {
//            Map<String, String> bizContent = JSONObject.parseObject(params.get("bizContent"), Map.class);
//            //logger.info("bizContent内容信息：" + bizContent);
//            String ordNo = bizContent.get("bizOrderNo");    //商户订单号
//            String orderNo = bizContent.get("orderNo");     //通联订单号
//            String amt = new BigDecimal(bizContent.get("amount")).divide(new BigDecimal("100")).toString();
//            String finishTime = bizContent.get("finishTime");
//
//            SuperPayOrder superPayOrder = null;
//            SuperPayOrder payOrder = new SuperPayOrder();
//            payOrder.setSuperOrderNo(ordNo);
//            payOrder.setStatus("0");
//            List<SuperPayOrder> superPayOrders = superPayOrderService.selectSuperPayOrderList(payOrder);
//            if(superPayOrders != null && superPayOrders.size() == 1){
//                superPayOrder = superPayOrders.get(0);
//            }
//
//            //获取油站的支付配置项信息
////            PayWay payWay = new PayWay();
////            payWay.setStationId(superPayOrder.getSuperPayId());
////            payWay.setAppType("1");
////            payWay.setUseType("0");             //使用类型
////            //获取该油站的支付类型
////            List<PayWay> payWayList = enterpriseService.selectStaPayWay(payWay);
////            params.put("key", payWayList.get(0).getTlAppKey());
//
//
//
//        }catch (Exception e) {//处理异常
//            e.printStackTrace();
//        }
//        finally{//收到通知,返回success
//            response.getOutputStream().write("success".getBytes());
//            response.flushBuffer();
//        }
//    }


    @RequestMapping(value = "/tLSVIPPayCallback", consumes = "application/x-www-form-urlencoded", method = RequestMethod.POST)
    @Transactional
    public void tLSVIPPayCallback(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("开通超级会员通联支付接收到通知");
        request.setCharacterEncoding("UTF-8");//通知传输的编码为GBK
        response.setCharacterEncoding("UTF-8");
        TreeMap<String,String> params = getParams(request);//动态遍历获取所有收到的参数,此步非常关键,因为收银宝以后可能会加字段,动态获取可以兼容
        logger.info("开通超级会员通联返回参数：" + params.toString());
        try {
            String ordNo = params.get("cusorderid");    //订单号
            String trxcode = params.get("trxcode");     //交易类型
            String trxamt = params.get("trxamt");       //交易金额
            SuperPayOrder superPayOrder = null;
            SuperPayOrder payOrder = new SuperPayOrder();
            payOrder.setSuperOrderNo(ordNo);
            payOrder.setStatus("0");
            List<SuperPayOrder> superPayOrders = superPayOrderService.selectSuperPayOrderList(payOrder);
            if(superPayOrders != null && superPayOrders.size() == 1){
                superPayOrder = superPayOrders.get(0);
            }
            //Station station = enterpriseService.selectStationById(superPayOrder.getStationId());
            String payType = "VSP501".equals(trxcode) ? "wx" : "zfb";
            boolean isSign = SybUtil.validSign(params, SybConstants.SYB_RSATLPUBKEY, SybConstants.SIGN_TYPE);         // 接受到推送通知,首先验签
            System.out.println("验签结果:"+isSign);
            if(isSign){
                // 0表示未支付  1表示已支付
                if(superPayOrder !=null && superPayOrder.getStatus().equals("0")){
                    logger.info("充值单号：" + ordNo);

                    if(StringUtils.isNotBlank(superPayOrder.getMobilePhone()) && superPayOrder.getSuperId() != null){
                        AppUserSuper userSuper = appUserSuperService.selectAppUserSuperById(superPayOrder.getSuperId());
                        //更新开通超级会员订单的支付状态以及更新用户超级会员状态
                        superPayOrder.setStatus("1");
                        superPayOrderService.updateSuperPayOrder(superPayOrder);
//
                        userSuper.setPhone(superPayOrder.getMobilePhone());
                        appUserSuperService.insertAppUserSuperPhone(userSuper,superPayOrder);

                    }else {
                        logger.info("无手机号");
                    }
                }else {
                    logger.info("此超级会员开通订单: "+ordNo+" 不存在或已完成支付！");
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally{//收到通知,返回success
            response.getOutputStream().write("success".getBytes());
            response.flushBuffer();
        }
    }

    /**
     * 通联 动态遍历获取所有收到的参数,此步非常关键,因为收银宝以后可能会加字段,动态获取可以兼容由于收银宝加字段而引起的签名异常
     * @param request
     * @return
     */
    private TreeMap<String, String> getParams(HttpServletRequest request){
        TreeMap<String, String> map = new TreeMap<String, String>();
        Map reqMap = request.getParameterMap();
        for(Object key:reqMap.keySet()){
            String value = ((String[])reqMap.get(key))[0];
            //System.out.println(key+";"+value);
            map.put(key.toString(),value);
        }
        return map;
    }

    //超级会员开通功能随行付回调功能
    @RequestMapping(value = "/getSVIPCallback", consumes = "application/json", method = RequestMethod.POST)
    @Transactional
    public JSONObject getSVIPCallback(@RequestBody JSONObject request) {
        logger.info("=========================超级会员开通功能随行付回调功能===============================");
        logger.info("超级会员开通功能随行付回调功能随行付回调返回过来的参数：" + request);
        //logger.info("ordNo信息：" + request.get("ordNo").toString());
        //logger.info("sign信息：" + request.get("sign").toString());
        Gson gson = new Gson();
        String sxfUuid = request.get("sxfUuid").toString();     //随行付落单号
        String payWay = request.get("payWay").toString();     //随行付交易方式
        String payTime = request.get("payTime").toString();   //随行付交易时间
        String uuid = request.get("uuid").toString();         //随行付交易流水号
        String mno = request.get("mno").toString();//发起交易的商户编号
        String ordNo = request.get("ordNo").toString();//商户生成的订单号
        String amt = request.get("amt").toString();//金额
        String buyerId = request.get("buyerId").toString();//用户登录
        String transactionId = request.get("transactionId").toString();//用户登录
        String drType = request.get("drType").toString();//借贷记标识 1-借,2-贷，3-其他
        String payType = request.get("payType").toString();//对订单的描述，取值范围：WECHAT:微信,ALIPAY:支付宝,UNIONPAY:
        String payBank = request.get("payBank").toString();//付款银行银行编码，例如 ICBC
        String pointAmount = request.get("pointAmount").toString();//代金券金额
        String totalOffstAmt = request.get("totalOffstAmt").toString();//消 费 者 付 款金额
        String settleAmt = request.get("settleAmt").toString();//商家入账金额
        String timeStamp = request.get("timeStamp").toString();//响应时间
        String sign = request.get("sign").toString();//签名
        String bizCode = request.get("bizCode").toString();//业务返回码
        String bizMsg = request.get("bizMsg").toString();//业 务 返 回 信息
        String openid = request.get("openid").toString();//微 信 或 支 付宝身份id()opendid userid
        String channelId = request.get("channelId").toString();//渠道商户号
        String subMechId = request.get("subMechId").toString();//子商户号
        String finishTime = request.get("finishTime").toString();//交易完成时间
        String clearDt = request.get("clearDt").toString();
        String settlementBatchNo = request.get("settlementBatchNo").toString();
        //String origOrdNo=request.get("origOrdNo").toString();//反交易退款异步通知
        //String origUuid=request.get("origUuid").toString();//token
        //String scene=request.get("scene").toString();//用户登录
        //String buyerAccount=request.get("buyerAccount").toString();//
        //String realRefundAmount=request.get("realRefundAmount").toString();//商家出账金额
        //String recFeeAmt=request.get("recFeeAmt").toString();//交易手续费
        //String recFeeRate=request.get("recFeeRate").toString();//交易手续费率
        //String refBuyerAmt=request.get("refBuyerAmt").toString();//消 费 者 到 账金额
        //String extend = extend=request.get("extend").toString();//备用

        //将业务参数存放在 JSON 对象中
        JSONObject reqData = new JSONObject();

        //支付场景
        if (request.containsKey("scene") && request.get("scene") != null) {
            String scene = request.get("scene").toString();
            reqData.put("scene", scene);
        }

        //recFeeRate
        if (request.containsKey("recFeeRate") && request.get("recFeeRate") != null) {
            String recFeeRate = request.get("recFeeRate").toString();
            reqData.put("recFeeRate", recFeeRate);
        }

        //消 费 者 到 账金额
        if (request.containsKey("refBuyerAmt") && request.get("refBuyerAmt") != null) {
            String refBuyerAmt = request.get("refBuyerAmt").toString();
            reqData.put("refBuyerAmt", refBuyerAmt);
        }

        //buyerAccount 支付宝买家登录账号  掩码；示例：135***1234
        if (request.containsKey("buyerAccount") && request.get("buyerAccount") != null) {
            String buyerAccount = request.get("buyerAccount").toString();
            reqData.put("buyerAccount", buyerAccount);
        }

        //备用
        if (request.containsKey("extend") && request.get("extend") != null) {
            String extend = request.get("extend").toString();
            reqData.put("extend", extend);
        }
        //优惠券参数
        if (request.containsKey("promotionDetail") && request.get("promotionDetail") != null) {
            String promotionDetail = request.get("promotionDetail").toString();
            reqData.put("promotionDetail", promotionDetail);
        }
        //商家出账金额
        if (request.containsKey("realRefundAmount") && request.get("realRefundAmount") != null) {
            String realRefundAmount = request.get("realRefundAmount").toString();
            reqData.put("realRefundAmount", realRefundAmount);
        }
        //szltFlag
        if (request.containsKey("szltFlag") && request.get("szltFlag") != null) {
            String szltFlag = request.get("szltFlag").toString();
            reqData.put("szltFlag", szltFlag);
        }
        //recFeeAmt
        if (request.containsKey("recFeeAmt") && request.get("recFeeAmt") != null) {
            String recFeeAmt = request.get("recFeeAmt").toString();
            reqData.put("recFeeAmt", recFeeAmt);
        }
        //szltRecfeeAmt
        if (request.containsKey("szltRecfeeAmt") && request.get("szltRecfeeAmt") != null) {
            String szltRecfeeAmt = request.get("szltRecfeeAmt").toString();
            reqData.put("szltRecfeeAmt", szltRecfeeAmt);
        }

        reqData.put("sxfUuid", sxfUuid);
        reqData.put("payWay", payWay);
        reqData.put("payTime", payTime);
        reqData.put("uuid", uuid);
        reqData.put("mno", mno);
        reqData.put("ordNo", ordNo);
        reqData.put("amt", amt);
        reqData.put("buyerId", buyerId);
        reqData.put("transactionId", transactionId);
        reqData.put("drType", drType);
        reqData.put("payType", payType);
        reqData.put("payBank", payBank);
        reqData.put("pointAmount", pointAmount);
        reqData.put("totalOffstAmt", totalOffstAmt);
        reqData.put("settleAmt", settleAmt);
        reqData.put("timeStamp", timeStamp);
        reqData.put("bizCode", bizCode);
        reqData.put("bizMsg", bizMsg);
        reqData.put("openid", openid);
        reqData.put("channelId", channelId);
        reqData.put("subMechId", subMechId);
        reqData.put("finishTime", finishTime);
        reqData.put("clearDt", clearDt);
        reqData.put("settlementBatchNo", settlementBatchNo);
        //reqData.put("realRefundAmount",realRefundAmount);
        //reqData.put("recFeeAmt",recFeeAmt);
        //reqData.put("recFeeRate",recFeeRate);
        //reqData.put("buyerAccount",buyerAccount);
        //reqData.put("origOrdNo",origOrdNo);
        //reqData.put("origUuid",origUuid);
        //reqData.put("scene",scene);
        //reqData.put("refBuyerAmt",refBuyerAmt);
        //reqData.put("extend",extend);
        //根据回调信息，先进行验签，验签后修改状态
        logger.info("打印参数信息" + gson.toJson(reqData));
        //不要对reqData排序 所以用LinkedHashMap
        HashMap<String, Object> result = JSON.parseObject(gson.toJson(reqData), LinkedHashMap.class, Feature.OrderedField);
        //验签
        String resultStr = RSASignature.getOrderContent(result);
        //JSONObject req = new JSONObject();
        System.out.println(resultStr);
        JSONObject req = new JSONObject();
//        if (RSASignature.doCheck(resultStr, sign, SXFPaySign.sxfPublic)) {
            req.put("code", "success");
            req.put("msg", "成功");
            logger.info("验签成功");
            SuperPayOrder superPayOrder = null;
            SuperPayOrder payOrder = new SuperPayOrder();
            payOrder.setSuperOrderNo(ordNo);
            payOrder.setStatus("0");
            List<SuperPayOrder> superPayOrders = superPayOrderService.selectSuperPayOrderList(payOrder);
            if (superPayOrders != null && superPayOrders.size() == 1) {
                superPayOrder = superPayOrders.get(0);
            }
            // 0表示未支付  1表示已支付
            if (superPayOrder != null && superPayOrder.getStatus().equals("0")) {
                logger.info("超级会员开通单号：" + ordNo);
                // Station station = enterpriseService.selectStationById(customerCardUseRecordInfo.getStationId());

                if (StringUtils.isNotBlank(superPayOrder.getMobilePhone()) && superPayOrder.getSuperId() != null) {
                    AppUserSuper userSuper = appUserSuperService.selectAppUserSuperById(superPayOrder.getSuperId());
                    //更新开通超级会员订单的支付状态以及更新用户超级会员状态
                    superPayOrder.setStatus("1");
                    superPayOrder.setPayTime(new Date());
                    superPayOrderService.updateSuperPayOrder(superPayOrder);
//
                    userSuper.setPhone(superPayOrder.getMobilePhone());
                    appUserSuperService.insertAppUserSuperPhone(userSuper,superPayOrder);
                } else {
                    logger.info("无手机号");
                }
            }else {
                logger.info("此超级会员开通订单: "+ordNo+" 不存在或已完成支付！");
            }
//        } else {
//            logger.info("验签失败");
//            req.put("code", "fail");
//            req.put("msg", "失败");
//        }
        logger.info("返回随行付参数信息：" + req.toString());
        return req;
    }

    /***
     * 公众号 云闪付扫呗  超级会员开通功能支付回调
     * @param params
     * @return
     */
    @RequestMapping(value = "/getYunPaySVIPCallback", consumes = "text/xml", method = RequestMethod.POST)
    @Transactional
    public net.sf.json.JSONObject getYunPaySVIPCallback(@RequestBody String params){
        net.sf.json.JSONObject result = new net.sf.json.JSONObject();       //返回给扫呗状态码
        logger.info("=============================云闪付扫呗  超级会员开通功能支付回调接口 ** 开始 ** ===============================================");
        YunPayCallBack yunPayCallBack = JSON.parseObject(params, YunPayCallBack.class);
        logger.info("云闪付扫呗  超级会员开通功能支付回调：" + params);System.out.println("云闪付扫呗  超级会员开通功能支付回调参数：" + params);
        if(yunPayCallBack.getResult_code() !=null && yunPayCallBack.getResult_code().equals("01")){
            logger.info("  -------------------------云闪付回调成功--------------------------  ");
            //返给云闪付状态码
            result.put("return_code", "01");
            result.put("return_msg", "success");
            //业务逻辑
            String ordNo = yunPayCallBack.getTerminal_trace();
            String amt = String.valueOf(new BigDecimal(yunPayCallBack.getTotal_fee()).divide(new BigDecimal("100")));

            SuperPayOrder superPayOrder = null;
            SuperPayOrder payOrder = new SuperPayOrder();
            payOrder.setSuperOrderNo(ordNo);
            payOrder.setStatus("0");
            List<SuperPayOrder> superPayOrders = superPayOrderService.selectSuperPayOrderList(payOrder);
            if(superPayOrders != null && superPayOrders.size() == 1){
                superPayOrder = superPayOrders.get(0);
            }

            // 0表示未支付  1表示已支付
            if(superPayOrder !=null && superPayOrder.getStatus().equals("0")){
                logger.info("充值单号：" + ordNo);
               // Station station = enterpriseService.selectStationById(customerCardUseRecordInfo.getStationId());

                String ccurPayType = "";
                switch (yunPayCallBack.getPay_type()){
                    case "010":
                        ccurPayType ="wx";
                        break;
                    case "020":
                        ccurPayType ="zfb";
                        break;
                }

                if(StringUtils.isNotBlank(superPayOrder.getMobilePhone()) && superPayOrder.getSuperId() != null){
                    AppUserSuper userSuper = appUserSuperService.selectAppUserSuperById(superPayOrder.getSuperId());
                    //更新开通超级会员订单的支付状态以及更新用户超级会员状态
                    superPayOrder.setStatus("1");
                    superPayOrderService.updateSuperPayOrder(superPayOrder);
//
                    userSuper.setPhone(superPayOrder.getMobilePhone());
                    appUserSuperService.insertAppUserSuperPhone(userSuper,superPayOrder);

                }else {
                    logger.info("无手机号");
                }
            }else {
                logger.info("此超级会员开通订单: "+ordNo+" 不存在或已完成支付！");
            }
        }else {
            result.put("return_code", "02");
            result.put("return_msg", "fail");
        }
        logger.info("返给云闪付结果信息：" + result);
        logger.info("=======================================云闪付扫呗  超级会员开通功能支付回调接口 ** 结束 ** ===============================================");
        return result;
    }



    @RequestMapping(value = "/test", method = RequestMethod.GET)
    @ApiOperation(value = "获取用户电子会员卡（储蓄卡）列表", httpMethod = "GET", notes = "获取用户电子会员卡（储蓄卡）列表")
    public void test(String orderNo){
        SuperPayOrder superPayOrder = null;
        SuperPayOrder payOrder = new SuperPayOrder();
        payOrder.setSuperOrderNo(orderNo);
        payOrder.setStatus("0");
        List<SuperPayOrder> superPayOrders = superPayOrderService.selectSuperPayOrderList(payOrder);
        if (superPayOrders != null && superPayOrders.size() == 1) {
            superPayOrder = superPayOrders.get(0);
        }
        AppUserSuper userSuper = appUserSuperService.selectAppUserSuperById(superPayOrder.getSuperId());
        //更新开通超级会员订单的支付状态以及更新用户超级会员状态
        superPayOrder.setStatus("1");
        superPayOrder.setPayTime(new Date());
        superPayOrder.setTransactionId("");
        superPayOrder.setMerchantsNumber("");
        superPayOrderService.updateSuperPayOrder(superPayOrder);
//
        userSuper.setPhone(superPayOrder.getMobilePhone());
        appUserSuperService.insertAppUserSuperPhone(userSuper,superPayOrder);
    }




    /**
     * 超级会员云化充值回调
     * @param request
     * @param response
     */
    @RequestMapping(value = "/getSVIPYunhuaCallback", consumes = "application/json", method = RequestMethod.POST)
    public void yunHuaCardNotice(HttpServletRequest request, HttpServletResponse response) {
        try {
            // 获取当前请求的域名
            //String requestUrl = request.getRequestURI();
            String data = JKPayUtil.getParamByStream(request);
            logger.info("云华开始超级会员充值回调:{}",data);
            JSONObject obj = JSON.parseObject(data);
            String status=obj.getString("status");
            if ("3".equals(status)) {

                BigDecimal amt=obj.getBigDecimal("txnAmt");
                String orderNo=obj.getString("clientSerialNo");
                String payTime=obj.getString("payTime");
                String transPayNo=obj.getString("transPayNo");
                String translnfoNo=obj.getString("transInfoNo");
                String payOrderNo=obj.getString("payOrderNo");
                String merchantDisAmt = obj.getString("merchantDisAmt");
                String sponsorDisAmt = obj.getString("sponsorDisAmt");
                String marketingDisAmt = obj.getString("marketingDisAmt");
                String platformDisAmt = obj.getString("platformDisAmt");
                String payAmt = obj.getString("payAmt");

                SuperPayOrder superPayOrder = null;
                SuperPayOrder payOrder = new SuperPayOrder();
                payOrder.setSuperOrderNo(orderNo);
                payOrder.setStatus("0");
                List<SuperPayOrder> superPayOrders = superPayOrderService.selectSuperPayOrderList(payOrder);
                if (superPayOrders != null && superPayOrders.size() == 1) {
                    superPayOrder = superPayOrders.get(0);
                }
                logger.info("超级会员充值订单信息：{}",superPayOrder);
                // 0表示未支付  1表示已支付
                if (superPayOrder != null && superPayOrder.getStatus().equals("0")) {
                    logger.info("超级会员开通单号：" + orderNo);
                    // Station station = enterpriseService.selectStationById(customerCardUseRecordInfo.getStationId());

                    if (StringUtils.isNotBlank(superPayOrder.getMobilePhone()) && superPayOrder.getSuperId() != null) {
                        AppUserSuper userSuper = appUserSuperService.selectAppUserSuperById(superPayOrder.getSuperId());
                        //更新开通超级会员订单的支付状态以及更新用户超级会员状态
                        superPayOrder.setStatus("1");
                        superPayOrder.setPayTime(new Date());
                        superPayOrder.setTransactionId(transPayNo);
                        superPayOrder.setMerchantsNumber(translnfoNo);
                        superPayOrderService.updateSuperPayOrder(superPayOrder);
//
                        userSuper.setPhone(superPayOrder.getMobilePhone());
                        appUserSuperService.insertAppUserSuperPhone(userSuper,superPayOrder);
                    } else {
                        logger.info("无手机号");
                    }
                }else {
                    logger.info("此超级会员开通订单: {}不存在或已完成支付！",orderNo);
                }
                response.getWriter().print("{\"code\":\"0000\"}");
            }
        }catch (Exception e){
            logger.error("云华开始超级会员充值回调异常");
            logger.error(e.getMessage(),e);
        }


    }
}
